/*    Copyright 2010 Tobias Marschall
 *
 *    This file is part of MoSDi.
 *
 *    MoSDi is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    MoSDi is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with MoSDi.  If not, see <http://www.gnu.org/licenses/>.
 */

package mosdi.fa;

import mosdi.util.BitArray;

public abstract class NFA {
	
	public abstract int alphabetSize();
	public abstract int stateCount();
	public abstract BitArray transition(BitArray activeStates, int character);
	public abstract BitArray acceptStates();
	public abstract BitArray startStates();
	
	/** Returns the number of matches associated with the given set of states. 
	 *  The default behavior is to return one match if at least one state
	 *  is an accept state.
	 */
	public int matchCount(BitArray states) {
		BitArray b = new BitArray(states);
		b.and(acceptStates());
		return b.numberOfOnes()==0?0:1;
	}
	
	public int countMatches(int[] string) {
		BitArray active = startStates();
		int i = 0;
		int result = 0;
		while (true) {
			result += matchCount(active);
			if (i==string.length) break;
			active = transition(active, string[i]);
			i += 1;
		}
		return result;
	}

	/** Returns the set of active states after reading the given string. */
	public BitArray read(int[] string) {
		BitArray active = startStates();
		for (int c : string) active = transition(active, c);
		return active;
	}
	
	/** Determines, whether the NFA accepts the given string, i.e. whether an
	 *  accept state is active after reading the string. */
	public boolean accepts(int[] string) {
		BitArray active = read(string);
		active.and(acceptStates());
		return !active.allZero();
	}
	
}
